package com.zhoug.common3.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 图片批量压缩工具
 * @Author 35574
 * @Date 2021/4/9
 * @Description
 */
public class ImageCompressUtil {
    private static final String TAG = ">>>ImageCompressUtil";
    private static final boolean DEBUG=false;

    //同时压缩最大并发10
    private ExecutorService executorService = Executors.newFixedThreadPool(10);
    private Context context;
    private List<String> images;
    private int compressWidth=720;
    private int compressHeight=1080;
    private int compressSize=200;
    private int count = 0;
    private List<String> result;
    private Callback callback;

    public interface Callback {
        void onResult(List<String> result);
    }

    public ImageCompressUtil(Context context,List<String> images) {
        this.context=context;
        this.images=images;

    }

    /**
     * 采样宽度
     * @param compressWidth
     * @return
     */
    public ImageCompressUtil setCompressWidth(int compressWidth) {
        this.compressWidth = compressWidth;
        return this;
    }

    /**
     * 采样高度
     * @param compressHeight
     * @return
     */
    public ImageCompressUtil setCompressHeight(int compressHeight) {
        this.compressHeight = compressHeight;
        return this;
    }

    /**
     * 压缩的最大大小 kb
     * @param compressSize
     * @return
     */
    public ImageCompressUtil setCompressSize(int compressSize) {
        this.compressSize = compressSize;
        return this;
    }

    /**
     * 结果回掉
     * @param callback
     * @return
     */
    public ImageCompressUtil setCallback(Callback callback) {
        this.callback = callback;
        return this;
    }


    /**
     * 压缩完成后回掉
     * 主线程回掉
     */
    private Handler handler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            count--;
            if (msg.what == 1) {
                result.add((String) msg.obj);
            }
            if (count == 0 && callback != null) {
                callback.onResult(result);
            }
            return true;
        }
    });

    /**
     * 开始压缩
     */
    public void start() {
        result=new ArrayList<>();
        count = images.size();
        for (int i = 0; i < images.size(); i++) {
            String sourcePath = this.images.get(i);
            executorService.execute(new Task(sourcePath));
        }
    }

    private class Task implements Runnable {
        private String source;

        public Task(String source) {
            this.source = source;
        }

        @Override
        public void run() {
            String destPath = null;
            boolean success = false;
            try {
                File sourceFile = new File(source);
                long length = sourceFile.length();
                sourceFile=null;
                if(length>0 && length<=compressSize*1024){
                    if (DEBUG) {
                        LogUtils.d(TAG, "无需压缩:" + source);
                    }
                    destPath=source;
                    success=true;
                }else{
                    if (DEBUG) {
                        LogUtils.d(TAG, "开始压缩:" + source);
                    }
                    byte[] bytes = BitmapUtils.compressTo(source, compressWidth, compressHeight, compressSize);
                    File externalCacheDir = context.getExternalCacheDir();
                    File file = new File(externalCacheDir, "compress/image" + FileUtils.getNameWithSuffix(source));
                    destPath = file.getAbsolutePath();
                    success = IOUtils.keepFile(destPath, bytes);
                    if (!success && file.exists()) {
                        //不成功则删除缓存文件
                        boolean delete = file.delete();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (DEBUG) {
                    File sourceFile = new File(source);
                    File destPathFile = new File(destPath);
                    LogUtils.d(TAG, FileUtils.getFormatFileSize(sourceFile.length()) + "==>" +
                            FileUtils.getFormatFileSize(destPathFile.length()));
                }
                Message message = handler.obtainMessage();
                message.obj = destPath;
                message.what = success ? 1 : 0;
                handler.sendMessage(message);
            }
        }
    }




}
